package com.tang.subject.domain.handler.subject;

import com.tang.subject.common.enums.CorrectEnum;
import com.tang.common.enums.DeleteEnum;
import com.tang.subject.common.enums.SubjectTypeEnum;
import com.tang.subject.domain.convert.JudgeSubjectConverter;
import com.tang.subject.domain.entity.SubjectAnswerBO;
import com.tang.subject.domain.entity.SubjectInfoBO;
import com.tang.subject.domain.entity.SubjectOptionBO;
import com.tang.subject.infra.basic.entity.pojo.SubjectJudge;
import com.tang.subject.infra.basic.service.SubjectJudgeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;
import java.util.Optional;

@Slf4j
@Service
public class JudgeTypeHandler implements SubjectTypeHandler {

    @Resource
    private SubjectJudgeService subjectJudgeService;

    /**
     * 获取题目类型
     *
     * @return com.tang.subject.common.enums.SubjectTypeEnum
     * @author Tang
     * @date 2024/2/4 14:16
     **/
    @Override
    public SubjectTypeEnum getSubjectType() {
        return SubjectTypeEnum.JUDGE;
    }

    /**
     * 添加题目
     *
     * @param subjectInfoBO 待插入的题目信息
     * @author Tang
     * @date 2024/2/4 14:22
     **/
    @Override
    public void add(SubjectInfoBO subjectInfoBO) {
        List<SubjectAnswerBO> optionList = subjectInfoBO.getOptionList();
        if (CollectionUtils.isEmpty(optionList)) {
            return;
        }
        SubjectAnswerBO subjectAnswerBO = optionList.get(0);
        SubjectJudge subjectJudge = new SubjectJudge();
        subjectJudge.setSubjectId(subjectInfoBO.getId());
        subjectJudge.setIsDeleted(DeleteEnum.UN_DELETED.getCode());
        subjectJudge.setIsCorrect(subjectAnswerBO.getIsCorrect());
        subjectJudgeService.insert(subjectJudge);
    }

    /**
     * 查询对应题目的具体选项信息
     *
     * @param subjectId 题目id
     * @return com.tang.subject.domain.entity.SubjectOptionBO
     * @author Tang
     * @date 2024/2/5 17:42
     **/
    @Override
    public SubjectOptionBO query(Long subjectId) {
        SubjectJudge subjectJudge = new SubjectJudge();
        subjectJudge.setSubjectId(subjectId);
        List<SubjectJudge> subjectJudges = subjectJudgeService.queryByCondition(subjectJudge);
        List<SubjectAnswerBO> answerBOS = JudgeSubjectConverter.INSTANCE.convertEntityToBoList(subjectJudges);
        SubjectOptionBO subjectOptionBO = new SubjectOptionBO();
        //取得判断题的答案
        SubjectAnswerBO answerBO = answerBOS.stream()
                .filter(Objects::nonNull)
                .findFirst()
                .orElse(null);
        //判断是否正确
        subjectOptionBO.setSubjectAnswer(Optional.ofNullable(answerBO)
                .map(i -> CorrectEnum.of(answerBO.getIsCorrect()))
                .orElse(CorrectEnum.WRONG.message));
        return subjectOptionBO;
    }
}
